package com.ymj.netty.server.medium;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ymj.netty.common.ServerRequest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  @Description: 中间人：netty服务端接收到请求，只需要调用本类的process方法即可处理对应业务，
 *                  process方法也是通过反射去调用对应的业务方法
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
public class Medium {

    /*存放所有远程调用方法*/
    static final ConcurrentHashMap<String,BeanMethod> allMethodMap;
    static {
        allMethodMap = new ConcurrentHashMap<>();
    }

    private Medium(){}

    /**
     * 单例：静态内部类
     * @return
     */
    public static Medium getInstance() {
        return Inner.medium;
    }

    private static class Inner{
        private static Medium medium = new Medium();
    }

    /**
     * 此方法通过反射去调用业务方法
     * 只需要在netty的handler中调用此方法，即可处理相应业务
     * @param request
     * @return
     */
    public Object process(ServerRequest request){
        Object result = null;
        try {
            String command = request.getCommand();
            BeanMethod beanMethod = allMethodMap.get(command);
            if (null == beanMethod){
                return null;
            }
            Object bean = beanMethod.getBean();
            Method method = beanMethod.getMethod();
            //此处为了简化，只获取一个参数
            Class<?> parameterType = method.getParameterTypes()[0];
            //获取方法参数
            Object param = JSONObject.parseObject(JSON.toJSONString(request.getContent()),parameterType);

            result = method.invoke(bean, param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }
}
